<template>
  <div class="app-container">
    <!-- 悬浮搜索栏 -->
    <div class="sticky-header">
      <div class="search-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文章标题"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 回到顶部按钮 -->
    <el-backtop :right="50" :bottom="50" />

    <!-- 导航分类 -->
    <el-row class="nav-cards" :gutter="20">
      <el-col
          v-for="(nav, index) in navItems"
          :key="index"
          :xs="24"
          :sm="6"
          :md="4"
          :lg="4"
          :xl="4"
      >
        <div
            class="nav-card"
            :style="{
          background: cardGradients[index % cardGradients.length],
          border: 'none'
        }"
            @click="handleNavClick(nav)"
        >
          <div class="nav-content">
            <div class="nav-icon">
              <component :is="navIcons[index]" class="icon" />
            </div>
            <div class="nav-title">{{ nav }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 内容卡片 -->
    <div v-loading="loading" class="content-cards">
      <div class="masonry-container" ref="masonryContainer">
        <div class="masonry-column" v-for="(column, index) in columns" :key="index">
          <div
            v-for="item in column"
            :key="item.infoId"
            class="masonry-item"
          >
            <div
              class="content-card"
              @mouseenter="activeCardId = item.infoId"
              @mouseleave="activeCardId = null"
            >
              <div class="card-image-container">
                <image-preview
                  :src="item.coverImg"
                  class="card-image"
                  :preview-src-list="infoList.map(i => i.coverImg)"
                />
                <div
                  class="image-overlay"
                  :class="{ 'active': activeCardId === item.infoId }"
                >
                  <el-button
                    type="primary"
                    size="small"
                    class="detail-btn"
                    @click.stop="goDetail(item.infoId)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>
              <div class="card-content">
                <h3 class="title">{{ item.title }}</h3>

                <div class="user-info">
                  <el-avatar
                    :size="24"
                    :src="getAvatarUrl(item.avatar)"
                  />
                  <span class="username">{{ item.userName || '匿名用户' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="infoList.length === 0" class="empty-card">
        <el-empty description="暂时没有相关内容哦~" image-size="200">
          <el-button type="primary" @click="getList">刷新试试</el-button>
        </el-empty>
      </div>

      <!-- 加载更多提示 -->
      <div v-if="hasMore" class="load-more">
        <el-button :loading="loading" type="text" @click="loadMore">加载更多</el-button>
      </div>
      <div v-else class="no-more">
        没有更多内容了~
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Document,
  User,
  DataBoard,
  KnifeFork,
  TrendCharts,
  Search
} from '@element-plus/icons-vue'
import { listInfo } from "@/api/healthSys/info"
import { listUsers } from "@/api/healthSys/users"
import { parseTime } from "@/utils/ruoyi"  // 确保导入时间格式化方法

const router = useRouter()
const masonryContainer = ref(null)

// 响应式数据
const navItems = ref(['健康资讯', '健康档案', '运动记录', '饮食记录', '健康趋势'])
const navIcons = [Document, User, DataBoard, KnifeFork, TrendCharts]
const cardGradients = [
  'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
  'linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%)',
  'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
]
const infoList = ref([])
const activeCardId = ref(null)  // 当前激活的卡片ID
const loading = ref(false)
const hasMore = ref(true)
const pageSize = 12
let currentPage = 1
const columns = ref([])
const columnCount = ref(4) // 默认4列
const searchQuery = ref('')

const queryParams = reactive({
  pageNum: 1,
  pageSize: pageSize,
  status: 1
})

// 用户头像映射
const userAvatarMap = ref(new Map())

// 获取用户头像
const getUserAvatar = (userId) => {
  if (!userId) return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  const user = userAvatarMap.value.get(userId.toString())
  console.log('当前用户ID:', userId, '用户数据:', user)
  if (!user || !user.headImg) return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  // 如果headImg已经是完整URL，直接返回
  if (user.headImg.startsWith('http')) {
    return user.headImg
  }
  // 否则拼接基础URL
  return import.meta.env.VITE_APP_BASE_API + user.headImg
}

// 加载用户数据
const loadUserData = async () => {
  try {
    const res = await listUsers({ pageSize: 1000 })
    if (res.code === 200 && res.rows) {
      // 使用userid作为key
      userAvatarMap.value = new Map(
        res.rows.map(u => [u.userid.toString(), u])
      )
      console.log('用户数据加载成功:', userAvatarMap.value)
    }
  } catch (error) {
    console.error('用户数据加载失败:', error)
  }
}

// 计算列数
const calculateColumns = () => {
  const width = window.innerWidth
  if (width >= 1200) {
    columnCount.value = 4
  } else if (width >= 992) {
    columnCount.value = 3
  } else if (width >= 768) {
    columnCount.value = 2
  } else {
    columnCount.value = 1
  }
}

// 分配卡片到列
const distributeItems = () => {
  const newColumns = Array(columnCount.value).fill().map(() => [])
  
  infoList.value.forEach(item => {
    // 找到最短的列
    let shortestColumnIndex = 0
    let shortestColumnHeight = newColumns[0].length

    for (let i = 1; i < newColumns.length; i++) {
      if (newColumns[i].length < shortestColumnHeight) {
        shortestColumnIndex = i
        shortestColumnHeight = newColumns[i].length
      }
    }
    
    newColumns[shortestColumnIndex].push(item)
  })
  
  columns.value = newColumns
}

// 监听窗口大小变化
const handleResize = () => {
  calculateColumns()
  distributeItems()
}

// 导航点击处理
const handleNavClick = (navName) => {
  const routeMap = {
    '健康资讯': '/user/info',
    '健康档案': '/user/records',
    '运动记录': '/user/sport',
    '饮食记录': '/user/diet',
    '健康趋势': '/user/trend'
  }
  if (routeMap[navName]) router.push(routeMap[navName])
}

// 获取数据方法
const getList = async (isLoadMore = false) => {
  if (loading.value) return
  
  try {
    loading.value = true
    // 先加载用户数据
    await loadUserData()
    
    const { code, rows, total: resTotal } = await listInfo(queryParams)

    if (code === 200) {
      if (isLoadMore) {
        const existingIds = new Set(infoList.value.map(item => item.infoId))
        const newItems = rows.filter(item => !existingIds.has(item.infoId))
        infoList.value = [...infoList.value, ...newItems]
      } else {
        infoList.value = rows
      }
      
      hasMore.value = infoList.value.length < resTotal
      currentPage++
      queryParams.pageNum = currentPage
      
      if (searchQuery.value.trim()) {
        const filteredList = infoList.value.filter(item => 
          item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
        infoList.value = filteredList
      }
      
      distributeItems()
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (searchQuery.value.trim()) {
    // 如果正在搜索，不加载更多
    return
  }
  getList(true)
}

// 监听滚动事件
const handleScroll = () => {
  if (!masonryContainer.value || searchQuery.value.trim()) return
  
  const container = masonryContainer.value
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const windowHeight = window.innerHeight
  const containerHeight = container.offsetHeight
  const containerTop = container.offsetTop

  // 当滚动到距离底部 200px 时加载更多
  if (scrollTop + windowHeight >= containerTop + containerHeight - 200) {
    loadMore()
  }
}

// 查看详情
const goDetail = (id) => {
  router.push({
    path: '/endangeredDetail/detail',
    query: { id }
  })
}

// 搜索处理
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    // 重置搜索状态，重新获取数据
    currentPage = 1
    queryParams.pageNum = 1
    getList()
    return
  }
  
  // 只过滤当前数据，不重新获取
  const filteredList = infoList.value.filter(item => 
    item.title.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
  
  infoList.value = filteredList
  distributeItems()
}

// 监听搜索框变化
watch(searchQuery, (newVal) => {
  if (!newVal) {
    // 清空搜索时重置状态
    currentPage = 1
    queryParams.pageNum = 1
    getList()
  }
})

onMounted(() => {
  calculateColumns()
  getList()
  window.addEventListener('scroll', handleScroll)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  window.removeEventListener('resize', handleResize)
})

// 监听数据变化
watch(() => infoList.value, () => {
  distributeItems()
})

const getAvatarUrl = (avatar) => {
  if (!avatar) return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
  if (avatar.startsWith('http')) return avatar
  return import.meta.env.VITE_APP_BASE_API + avatar
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f8fafc;
  position: relative;
}

.sticky-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 15px 0;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border-radius: 8px;

  .search-container {
    max-width: 400px;
    margin: 0 auto;
    padding: 0 20px;

    .search-input {
      :deep(.el-input__wrapper) {
        background: #f8fafc;
        border-radius: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        
        &:hover, &:focus {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
}

// 修改回到顶部按钮样式
:deep(.el-backtop) {
  background-color: #fff;
  color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &:hover {
    background-color: #409eff;
    color: #fff;
    transform: scale(1.1);
  }
}

.nav-cards {
  margin-bottom: 40px;
  display: flex;
  flex-wrap: wrap;
  margin-left: -10px !important;
  margin-right: -10px !important;

  // 列项样式
  .el-col {
    flex: 1 0 auto;
    max-width: 20%;
    padding: 0 10px !important;
    margin-bottom: 20px;

    // 响应式调整
    @media (max-width: 1199px) { // 中等屏幕适配
      max-width: 25%;
      flex: 0 0 25%;
    }
    @media (max-width: 991px) { // 平板适配
      max-width: 33.3333%;
      flex: 0 0 33.3333%;
    }
    @media (max-width: 767px) { // 手机适配
      max-width: 50%;
      flex: 0 0 50%;
    }
    @media (max-width: 480px) { // 小手机
      max-width: 100%;
      flex: 0 0 100%;
    }
  }

  .nav-card {
    height: 160px;
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 100%; // 新增宽度控制
    min-width: 180px; // 防止内容过小变形

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
    }

    .nav-content {
      padding: 30px;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: white;

      // 响应式调整
      @media (max-width: 1199px) {
        padding: 20px;
      }

      .nav-icon {
        margin-bottom: 15px;
        transition: transform 0.3s ease;

        .icon {
          width: 40px;
          height: 40px;
          @media (max-width: 991px) {
            width: 35px;
            height: 35px;
          }
        }
      }

      .nav-title {
        font-size: 18px;
        font-weight: 500;
        letter-spacing: 1px;
        text-align: center;
        @media (max-width: 1199px) {
          font-size: 16px;
        }
        @media (max-width: 767px) {
          font-size: 14px;
        }
      }
    }
  }
}

.content-cards {
  margin-bottom: 40px;
}

.masonry-container {
  display: flex;
  gap: 20px;
  padding: 0 20px;
}

.masonry-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.masonry-item {
  break-inside: avoid;
}

.content-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);

  &:hover {
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    transform: translateY(-5px);
  }

  .card-image-container {
    position: relative;
    width: 100%;
    overflow: hidden;

    .card-image {
      width: 100%;
      height: auto;
      display: block;
      transition: transform 0.3s ease;
    }

    .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
      opacity: 0;
      transition: opacity 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &.active {
        opacity: 1;
      }

      .detail-btn {
        padding: 10px 25px;
        font-weight: 500;
        letter-spacing: 0.5px;
        transition: transform 0.2s ease;

        &:hover {
          transform: scale(1.05);
        }
      }
    }
  }

  .card-content {
    padding: 15px;

    .title {
      font-size: 16px;
      font-weight: 600;
      color: #2d3748;
      margin: 0 0 12px 0;
      line-height: 1.4;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .meta-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #718096;
      margin-bottom: 10px;

      .category-tag {
        background: #e2e8f0;
        padding: 4px 8px;
        border-radius: 4px;
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 10px;

      .username {
        font-size: 14px;
        color: #4a5568;
      }
    }
  }
}

.empty-card {
  background: white;
  border-radius: 12px;
  padding: 40px 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
  margin: 20px;
}

.load-more, .no-more {
  text-align: center;
  padding: 20px;
  color: #666;
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .masonry-container {
    gap: 10px;
    padding: 0 10px;
  }

  .masonry-column {
    gap: 10px;
  }

  .content-card {
    .card-content {
      padding: 10px;

      .title {
        font-size: 14px;
      }

      .user-info {
        .username {
          font-size: 12px;
        }
      }
    }
  }
}
</style>
